package com.example.lenovo.telephonerecord;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private MyConnection conn;
    private BindService.MyBinder binder ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void start(View view) {
       // startActivity(new Intent(getApplicationContext(),RecordService.class));
        Intent service = new Intent(this,BindService.class);
        conn = new MyConnection();
        //  开启服务时操作的选项，这个自动创建service
        bindService(service,conn,BIND_AUTO_CREATE);
        //  bindService  --> MyConnection  --> Ibinder  -->  onBind  -- > new Binder()  -- >   Binder中写逻辑
    }
    private class  MyConnection implements ServiceConnection {

        /**
         * IBinder 一定要有返回值，这个方法才会被调用
         * @param name
         * @param service
         */
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (BindService.MyBinder) service;
        }

        /**
         * 正常情况下，关闭服务（退出）时，不会调用，只有onBind方法不为null，才会调用
         * @param name
         */
        public void onServiceDisconnected(ComponentName name) {

        }
    }
    public void stop(View view){
       // stopService(new Intent(getApplicationContext(),RecordService.class));
        unbindService(conn);
    }
    public void callServiceMethod(View view) {
        binder.callShowToast("哈哈哈哈");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  bind绑定后，要在这个方法中解绑
        //  把service关闭，解除跟当前activity的绑定
        unbindService(conn);
    }
}
